<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\tool;

/**
 * 消息组装者
 */
class MessageBuilder
{

    const NOTICE    = 'notice';
    const WARNING   = 'warning';
    const SYSTEM    = 'system';
    const FORBIDDEN = 'forbidden';
    const SUCCESS   = 'success';
    protected $action = '';

    public $closeClient = false;

    protected $data = [];

    public function __construct(bool $closeClient = false, string $action = self::NOTICE)
    {
        $this->action = $action;
        $this->closeClient = $closeClient;
    }

    public function write(string $message, int $code = 403, array $data = [])
    {
        $this->data = [
            'code'      => $code,
            'notice'    => $message,
            'data'      => $data,
            'action'    => $this->action,
            'timestamp' => time()
        ];

        return $this;
    }

    public function __toString()
    {
        return json_encode($this->data, JSON_UNESCAPED_UNICODE);
    }
}
